<?php
/**
 * Created by PhpStorm.
 * User: yzapple
 * Date: 2018/1/17
 * Time: 上午8:52
 */

namespace app\doctor\controller;


use Aliyun\Core\Config;
use app\common\controller\Commoncontroller;
use app\common\library\DoctorAuth;

use app\common\model\Doctor;
use app\common\model\Patient;
use app\common\model\Patientcase;
use app\common\model\PatientCaseTypee;

class Basecontroller extends Commoncontroller
{
    /**
     * 返回码,默认为null,当设置了该值后将输出json数据
     * @var int
     */
    protected $code = null;

    /**
     * 返回内容,默认为null,当设置了该值后将输出json数据
     * @var mixed
     */
    protected $data = null;

    /**
     * 返回文本,默认为空
     * @var mixed
     */
    protected $msg = '';
    /**
     * 布局模板
     * @var string
     */
    protected $layout = 'default';

    /**
     *
     * @var DoctorAuth
     */
    protected $doctor = null;
    /**
     * 无需登录的方法，默认全部都无需登录
     * @var array
     */
    protected $noNeedLogin = ['*'];

    public function _initialize()
    {
        parent::_initialize();

        //定义要验证的操作
        // 提交数据会通过闭包函数加载
        $this->adminLog = [
            'patient' => [
                'patient'=>[
                    'action' => ['index','add_patient','check_detail'],
                    'model' => 'Patient',
                    'func' =>   function($data,$userId,$admin_type){
                        $model = new Patient;
                        $result =  $model::getPatientAdminLog('index',$data,$userId,$admin_type);
                        return $result;
                    },

                ],
            ],
                'index' => [
                    'doctor'=>[
                        'action' => ['index'],
                        'model' => 'Doctor',
                        'func' =>   function($data,$userId,$admin_type){
                            $model = new Doctor;
                            $result =  $model::addDoctorAdminLog('index',$data,$userId,$admin_type);
                            return $result;
                        },

                    ]
                ],
            'record' => [
                'patientcase'=>[
                    'action' => ['index','add_record','check_detail'],
                    'model' => 'patientcase',
                    'func' =>   function($data,$userId,$admin_type){
                        $model = new Patientcase;
                        $result =  $model::getPatientCaseAdminLog('index',$data,$userId,$admin_type);
                        return $result;
                    },

                ],
            ],




        ];

        $this->isSendMsg = [
            'record' => [
                'patientcase'=>[
                    'action' => ['add_record'],
                    'model' => 'patientcase',
                    'msg_type' => 'tpl1',
                    'func' =>   function($record_id){
                        $model = new Patientcase;
                        $result =  $model::sendMsgToPatient($record_id);
                        return $result;
                    },

                ],
            ]
        ];

        $url = '';
        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());

        $path = '/' . $modulename . '/' . str_replace('.', '/', $controllername) . '/' . $actionname;
        $this->doctor = DoctorAuth::instance();
        // 如果有使用模板布局

        $this->doctor->setRequestUri($path);
        $this->doctor->init();
        if(MODULE_NAME == 'admin') {

        }else{
            // 检测是否需要验证登录
            if (!$this->doctor->match($this->noNeedLogin)) {
//            var_dump("cc");
                $this->checkLogin();
            }
        }
        $this->assign('pageurl',$this->request->url());

        $this->assign('url',$this->request->action());
        $this->assign("doctor", $this->doctor);


    }

    public function __construct()
    {
        parent::__construct();


        //添加log日志+数据
        //获取当前的模块
        $admin_type = 2;
        //
        if(MODULE_NAME == 'admin'){
            $admin_type = 1;

        }

        $data = $this->request->param();
  /*   print_r($data);
    exit;*/
        $this->addAdminLog($data,$admin_type);
    }



    /**
     * 添加记录日志问题
     **/
    protected function addAdminLog($data,$admin_type){
        //获取当前的路径
        $controllerName = strtolower(CONTROLLER_NAME);
        $actionName = strtolower(ACTION_NAME);
        $path = $controllerName."/".$actionName;

        $arr_log = $this->checkAdminLog($controllerName,$actionName,$this->adminLog);
        //print_r($arr_log);
       // exit;
        //验证当前路径是否在数组中,则记录数据
        if($arr_log){

            if($this->request->post()){
                $scene = '';
                if(isset($arr_log['validate']) && $arr_log['validate']){

                    $scene = $actionName;
                }

                $result = $this->validate($data,$arr_log['model'].'.'.$scene);

                if(true !== $result){
                    // 验证失败 输出错误信息
                    return ['flag'=>'error','msg'=>$this->error($result),'url'=>''];
                }
            }


            //使用闭包函数
            if(MODULE_NAME == 'admin') {
                $userId = session('adminuid');
            }else{
                $userId =$this->doctor->id;
            }
            $result  =  $arr_log['func']($data,$userId,$admin_type);
            $url = '';
        // var_dump($result);
            if(isset($result['url'])){
                $url = url($result['url']);
            }
            $record_id = '';
            if(isset($result['record_id'])){
                $record_id = $result['record_id'];
            }

            if($result['flag'] == 'success'){

                //验证是否要发送短信+短信之后的回复情况
                $this->checkSendMsg($controllerName,$actionName,$record_id,$this->isSendMsg);

            $this->success($result['msg'],$url);
            }else if($result['flag'] == 'error'){
              $this->error($result['msg'],$url);
            }else{

            }

        }
    }





    /**
     * 当前对象回调成员方法
     * @param string $method
     * @param array|bool $data
     * @return bool
     */
    protected function _callback($method, &$data)
    {
        foreach ([$method, "_" . $this->request->action() . "{$method}"] as $_method) {
            if (method_exists($this, $_method) && false === $this->$_method($data)) {
                return false;
            }
        }
        return true;
    }
//    /**
//     * 列表集成处理方法
//     * @param Query $dbQuery 数据库查询对象
//     * @param bool $isPage 是启用分页
//     * @param bool $isDisplay 是否直接输出显示
//     * @param bool $total 总记录数
//     * @param array $result
//     * @return array|string
//     */
//    protected function _list($dbQuery = null, $isPage = true, $isDisplay = true, $total = false, $result = [])
//    {
//        $db = is_null($dbQuery) ? model($this->model) : (is_string($dbQuery) ? model($dbQuery) : $dbQuery);
////        // 列表排序默认处理
////        if ($this->request->isPost() && $this->request->post('action') === 'resort') {
////            $data = $this->request->post();
////            unset($data['action']);
////            foreach ($data as $key => &$value) {
////                if (false === $db->where('id', intval(ltrim($key, '_')))->setField('sort', $value)) {
////                    $this->error('列表排序失败, 请稍候再试');
////                }
////            }
////            $this->success('列表排序成功, 正在刷新列表', '');
////        }
//        // 列表数据查询与显示
//        if (null === $db->getOptions('order')) {
//            $fields = $db->getTableFields($db->getTable());
//            in_array('sort', $fields) && $db->order('sort asc');
//        }
//         $this->assign('url',$this->request->url() );
//
//        if ($isPage) {
//            $rows = intval($this->request->get('rows', cookie('rows')));
//            cookie('rows', $rows >= 1 ? $rows : 2);
//            $page = $db->paginate($rows, $total, ['query' => $this->request->get('', '', 'urlencode')]);
//            list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['href="$1"', 'pagination pull-right']];
//            $cc = $page->total();
//            $cc2 = $page->lastPage();
//            $currentPage = $page->currentPage();
//            list($result['list'], $result['page'],$result['alltotol'],$result['allpage'],$result['currentpage']) = [$page->all(), preg_replace($pattern, $replacement,$page->render()),$cc,$cc2,$currentPage];
//        } else {
//            $result['list'] = $db->select();
//        }
//        if (false !== $this->_callback('_data_filter', $result['list']) && $isDisplay) {
//            !empty($this->title) && $this->assign('title', $this->title);
//            return $this->fetch('', $result);
//        }
//
//        return json($result);
//    }
//



    protected function checkLogin()
    {
//        var_dump($this->doctor->isLogin());
//        //检测是否登录
        if (!$this->doctor->isLogin()) {
//        var_dump("啛啛喳喳");

            return $this->redirect(url('login/index'));
        }
    }
}
